#!/usr/bin/env python

BLOG_BOX            = 'blog'
DEFAULT_CATEGORY    = 'technology'
CATEGORY_LIST       = ('technology', 'more')
TEMPLATE_FILE       = 'template.html'
PAGE_UNIT           = 3
RCOMMENT_UNIT       = 10
ONE_DAY             = 60 * 60 * 24


import md5
import os
import pprint
import sys
import time
import uuid

from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext.webapp.util import run_wsgi_app

from common import message


def bbody(req, user):
    def get_category():
        category = req.get('c', DEFAULT_CATEGORY)
        return category

    def get_author_url(_url):
        url = _url.strip()
        if not url:
            return ''
        if not (url[:7].lower() == 'http://' or url[:8].lower() == 'https://'):
            url = 'http://%s' % url 
        url = '%s%s' % (url[:5].lower(), url[5:])
        return url 

    params      = { 
        'rt'        : 'POST_READ' if req.get('u', None) and not req.get('rt', None) \
            else req.get('rt', 'POST_LIST').upper(),
        'user'      : user,
        'uid'       : req.get('u', None),
        'category'  : get_category(),
    }
    control     = { 'bheader' : True, 'bbody' : True, 'bfooter' : True }
    hheader     = { }
    bbody       = None
    return_url  = None
    void        = { }

    if params['rt'] == 'POST_LIST':
        try:
            _cur_page = max(0, int(req.get('p', 0)))
        except ValueError:
            _cur_page = 0
        params['messages'], \
            params['prev_page'], params['cur_page'], params['next_page'] = \
            message.post_list(BLOG_BOX, params['category'], 
                PAGE_UNIT, _cur_page, False)
        void['page_title'] = params['category']
        if params['messages']:
            for _message in params['messages']:
                if ONE_DAY < (time.time() - time.mktime(_message.created_date.timetuple())):
                    _message.created_date_adayago = False
                else:
                    _message.created_date_adayago = True

    elif params['rt'] == 'POST_READ':
        params['messages'] = message.post_read(BLOG_BOX, params['uid'])
        if params['messages']:
            params['category'] = params['messages'][0].category
            void['page_title'] = params['messages'][0].title
            for _message in params['messages']:
                _message.author_email_md5 = md5.new(_message.author_user.email()).hexdigest()
                if ONE_DAY < (time.time() - time.mktime(_message.created_date.timetuple())):
                    _message.created_date_adayago = False
                else:
                    _message.created_date_adayago = True

    elif params['rt'] == 'POST_ADD' and user.admin:
        category = get_category()
        if not category in CATEGORY_LIST:
            category = DEFAULT_CATEGORY
        message_properties = {
            'uid'               : None,
            'box'               : BLOG_BOX,
            'category'          : category,
            'title'             : req.get('t', '').strip(),
            'content'           : req.get('ct', '').strip(),
            'message_status'    : 'PUBLIC',
            'comment_status'    : 'OPENED',
            'author_user'       : params['user'].user,
        }
        message.post_add(message_properties)
        return_url = '#'

    elif params['rt'] == 'POST_EDIT' and user.admin:
        category = get_category()
        if not category in CATEGORY_LIST:
            category = DEFAULT_CATEGORY
        message_properties = {
            'uid'               : params['uid'],
            'box'               : BLOG_BOX,
            'category'          : category,
            'root_post'         : True,
            'title'             : req.get('t', '').strip(),
            'content'           : req.get('ct', '').strip(),
            'message_status'    : 'PUBLIC',
            'author_user'       : params['user'].user,
        }
        message.post_add(message_properties)
        return_url = '#'

    elif params['rt'] == 'COMMENT_ADD':
        return_url = '#'
        if params['category'] in CATEGORY_LIST:
            uid = req.get('u', '').strip()
            if uid:
                message_properties = {
                    'uid'               : uid,
                    'box'               : BLOG_BOX,
                    'category'          : params['category'],
                    'content'           : req.get('ct', '').strip(),
                    'message_status'    : 'PUBLIC',
                    'comment_status'    : 'OPENED',
                    'author_user'       : params['user'].user,
                    'author_nickname'   : req.get('nn', '').strip(),
                    'author_ip'         : None if user.admin else req.remote_addr,
                    'author_ua'         : None if user.admin else req.user_agent.strip(),
                    'author_url'        : get_author_url(req.get('url', '')),
                }
                message.post_add(message_properties)
                return_url = '?u=%s#bottom' % uid

    void['rcomments'] = get_comment_recent_list(params['category'])

    if not return_url:
        path = os.path.join(os.path.dirname(__file__), TEMPLATE_FILE)
        bbody = template.render(path, params)      

    return (control, hheader, bbody, return_url, void)

def get_post_total(category):
    return message.post_total(BLOG_BOX, category)

def get_comment_recent_list(category):
    rcomment_num = 10
    return message.comment_recent_list(BLOG_BOX, category, rcomment_num)

